import Taro, { Component, Config } from '@tarojs/taro'
import { Button, Form, Image, Input, View } from '@tarojs/components'
import classNames from 'classnames'
import './index.scss'
import lodash from '@/utils/lodash'
import { PAY_TYPE } from '@/config/types'
import { getShopList } from '@/api/merchantApi'
import { toIntegralOrderInfoPage } from '@/utils/page_router'
import { getAddressList, getUserInfo } from '@/api/userApi'
import { asyncCalcScoresOrder, getConnectUser, submitScoresOrder } from '@/api/orderApi'
import { Loading, ShopSelect, AddressSelect, IconGold } from '@/components/index'
import { headImg, getThumbnailConfig, getSubscribeMessage } from '@/utils/utils'

//  获取地址
const getAddress = (list, info) => {
  if (info && info.id) {
    return info
  } else {
    const arr = list.filter(i => i.isDefault)
    return (arr.length >= 1 ? lodash.head(arr) : (lodash.head(list) || {}))
  }
}

export default class Index extends Component {
  state:any
  config: Config = {
    backgroundTextStyle: "dark",
    navigationBarTextStyle: process.env.navigationBarTextStyle,
    navigationBarBackgroundColor: process.env.backgroundColor
  }

  constructor() {
    super(...arguments)
    this.state = {
      type: 0,
      typeList: [
        { title: '快递配送', value: 0 },
        { title: '到店自提', value: 1 }
      ],
      payType: PAY_TYPE.WECHAT,
      loading: true,
      isScore: false,
      orderInfo: {},
      showShop: false,
      showAddress: false,
      userInfo: {},
      shopInfo: {},
      addressInfo: {},
      connectSnap: {},
      shopList: [],
      productList: [],
      addressList: [],
    }
  }

  componentDidMount () {
    this.initOrder()
    this.getConnectUser()
  }

  async componentDidShow() {
    const { loading, addressInfo } = this.state
    if (!loading) {
      wx.showLoading({title: '请稍后', mask: true})
      const addressRes = await getAddressList()
      this.setState({
        addressInfo: getAddress(addressRes.data, addressInfo),
        addressList: addressRes.data
      }, () => {
        wx.hideLoading()
      })
    }
  }

  //  初始化订单
  async initOrder() {
    const { addressInfo } = this.state
    const shopRes = await getShopList()
    const addressRes = await getAddressList()
    const userRes = await getUserInfo()

    this.setState({
      userInfo: userRes.data,
      shopInfo: lodash.head(shopRes.data),
      shopList: shopRes.data,
      addressInfo: getAddress(addressRes.data, addressInfo),
      addressList: addressRes.data
    }, () => {
      this.calcOrder()
    })
  }

  //  计算订单
  calcOrder() {
    const { params } = this.$router
    const { loading, orderInfo, isScore, type, typeList } = this.state
    const data = {
      id: orderInfo.id,
      distribute: typeList[type]['value'],
      productList: [{ id: params.id, skuId: params.skuId, number: params.number }],
      scoreDiscount: isScore ? orderInfo.deductScoreAmount : undefined
    }

    if (!loading) {
      wx.showLoading({title: '请稍后', mask: true})
    }
    asyncCalcScoresOrder(data).then(res => {
      const { data } = res
      this.setState({
        orderInfo: data,
        productList: data.productList,
      }, () => {
        wx.hideLoading()
        this.setState({
          loading: false
        })
      })
    })
  }

  //  获取自提记录填写的信息
  getConnectUser() {
    getConnectUser().then(res => {
      this.setState({
        connectSnap: res.data || {}
      })
    })
  }

  //  切换渲染类型
  onSwitchType(type) {
    this.setState({
      type
    }, () => {
      this.calcOrder()
    })
  }

  //  显示选择弹出窗口
  showSelectPopup(name, bool) {
    this.setState({
      [name]: bool
    })
  }

  //  确认选择
  onConfirmSelect(name, info) {
    this.setState({
      [name]: info
    }, () => {
      if(name === 'addressInfo') {
        this.calcOrder()
      }
    })
  }

  //  提交表单
  onSubmit(e) {
    const { value } = e.detail
    const { type, orderInfo, addressInfo, shopInfo }:any = this.state
    const data:any = {
      id: orderInfo.id
    }
    Object.keys(value).map(name => {
      lodash.set(data, name, value[name])
    })

    if (type === 0 && !addressInfo) {
      wx.showToast({ title: '请选择收货地址', icon: 'none' })
      return
    }

    if (type === 1 && !shopInfo) {
      wx.showToast({ title: '请选择自提店铺', icon: 'none' })
      return
    }

    if (type === 1 && !data.connectSnap.name) {
      wx.showToast({ title: '请输入联系人', icon: 'none' })
      return
    }

    if (type === 1 && !data.connectSnap.telephone) {
      wx.showToast({ title: '请输入联系电话', icon: 'none' })
      return
    }

    //  配送方式
    if (type === 0) {
      Object.assign(data, {
        addressSnap: addressInfo
      })
    }

    //  自提方式
    if (type === 1) {
      Object.assign(data, {
        cooperateShopId: shopInfo.id,
        cooperateShopAddress: shopInfo,
      })
    }

    //  订阅通知模板
    const tmplIds = type ? getSubscribeMessage('checkOrder') : getSubscribeMessage('postOrder')
    wx.requestSubscribeMessage({
      tmplIds,
      complete: () => {
        wx.showLoading({title: '请稍后', mask: true})
        submitScoresOrder(data).then(res => {
          wx.hideLoading()
          wx.showToast({ title: '兑换成功', icon: 'success', complete: function () {
              toIntegralOrderInfoPage(res.data, true)
            }
          })
        })
      }
    })
  }

  render () {
    const { loading, type, typeList, addressInfo, shopInfo, connectSnap, addressList, productList, shopList, showShop, showAddress, orderInfo } = this.state
    return (<View className='index'>
      {loading && <Loading isCover/>}
      <View className='index-scroll'>
        <View className='index-head delivery-type'>
          <View className='type-list d-f a-i-f-e'>
            {typeList.map((i, k) => {
              return (<View key={k} className={classNames('type-item d-f a-i-c j-c-c', type === k && 'active')} onClick={this.onSwitchType.bind(this, k)}>{i.title}</View>)
            })}
          </View>
          {type == 0 && <View className='delivery-box d-f a-i-c j-c-b' onClick={this.showSelectPopup.bind(this, 'showAddress', true)}>
            {addressInfo.telephone && <View className='address-box'>
              <View className='base-address d-f a-i-c '>
                <View className='user-name t-o-e'>{addressInfo.name}</View>
                <View className='user-phone'>{addressInfo.telephone}</View>
              </View>
              <View className='address-text t-o-e-2'>{addressInfo.city} {addressInfo.detail}</View>
            </View>}
            {!addressInfo.telephone && <View className='address-box'>设置收货地址</View>}
            <View className='bnn-icon right-icon'>&#xe866;</View>
          </View>}
          {type == 1 && <View className='delivery-box d-f a-i-c j-c-b' onClick={this.showSelectPopup.bind(this, 'showShop', true)}>
            <View className='address-box'>
              <View className='base-address d-f a-i-c '>
                <View className='user-name t-o-e'>{shopInfo.shopName}</View>
                <View className='user-phone'>{shopInfo.phone}</View>
              </View>
              <View className='address-text t-o-e-2'>{shopInfo.address}</View>
            </View>
            <View className='bnn-icon right-icon'>&#xe866;</View>
          </View>}
        </View>

        <View className='order-card goods-list'>
          {productList.map(i => {
            return (<View key={i.id} className='goods-item thin-border__b'>
              <Image src={getThumbnailConfig(headImg(i.images), 320, 320)} className='goods-img' lazyLoad/>
              <View className='other-box d-f f-d-c j-c-b'>
                <View className='other-head'>
                  <View className='goods-name t-o-e-2'>{i.name}</View>
                  {i.skuId && <View className='attr-name t-o-e'>{i.specSnap}</View>}
                </View>
                <View className='other-foot d-f a-i-b j-c-b'>
                  <View className='goods-price bnn-number'>
                    {Number(i.salePrice)} <IconGold/>
                  </View>
                  <View className='goods-num'>x{i.number}</View>
                </View>
              </View>
            </View>)
          })}
        </View>
        <Form onSubmit={this.onSubmit.bind(this)}>
          <View className='order-card'>
            <View className='card-list'>
              {/*{type === 0 && <View className='list-item thin-border__b'>*/}
              {/*  <View className='item-left'>*/}
              {/*    /!*<View className='item-icon'></View>*!/*/}
              {/*    <View className='item-title'>快递费用</View>*/}
              {/*  </View>*/}
              {/*  <View className='item-right bnn-number'>￥{orderInfo.freightAmount}</View>*/}
              {/*</View>}*/}
              {type === 1 && <View className='list-item thin-border__b'>
                <View className='item-left'>
                  <View className='item-title'>联系人</View>
                </View>
                <View className='item-right'>
                  <Input name='connectSnap.name' value={connectSnap.name} maxLength={16} placeholder='请填写您的联系姓名' className='item-input'/>
                </View>
              </View>}
              {type === 1 && <View className='list-item thin-border__b'>
                <View className='item-left'>
                  <View className='item-title'>联系电话</View>
                </View>
                <View className='item-right'>
                  <Input name='connectSnap.telephone' type='number' value={connectSnap.telephone} maxLength={11} placeholder='请填写您的联系电话' className='item-input'/>
                </View>
              </View>}
              <View className='list-item f-w-w'>
                <View className='item-left'>
                  <View className='item-title'>备注信息</View>
                </View>
                <View className='item-right'>
                  <Input name='remark' maxLength={255} placeholder='请添加备注（150字以内）' className='item-input'/>
                </View>
              </View>
            </View>
          </View>
          {/*<View className='order-card'>*/}
          {/*  <View className='total-list'>*/}
          {/*    <View className='list-item'>*/}
          {/*      <View className='item-left'>商品总价：</View>*/}
          {/*      <View className='item-right bnn-number'>{orderInfo.productAmount} <IconGold/></View>*/}
          {/*    </View>*/}
          {/*    <View className='list-item'>*/}
          {/*      <View className='item-left'>运费：</View>*/}
          {/*      <View className='item-right bnn-number'>￥{formatAmount(orderInfo.freightAmount)}</View>*/}
          {/*    </View>*/}
          {/*  </View>*/}
          {/*</View>*/}
          <View className='index-foot--height'/>
          <View className='index-foot d-f a-i-c fy-popup fy-popup--bottom'>
            <View className='total-num'>共{productList.length}件</View>
            <View className='total-money d-f j-c-e'>合计：<View className='money-num bnn-number'>{orderInfo.payAmount} <IconGold/></View></View>
            <Button formType="submit" className='buy-now d-f a-i-c j-c-c' hoverClass='hover-class--btn'>立即兑换</Button>
          </View>
        </Form>
      </View>
      <ShopSelect isOpened={showShop} item={shopInfo} list={shopList} onClose={this.showSelectPopup.bind(this, 'showShop', false)} onConfirm={this.onConfirmSelect.bind(this, 'shopInfo')}/>
      <AddressSelect isOpened={showAddress} item={addressInfo} list={addressList} onClose={this.showSelectPopup.bind(this, 'showAddress', false)} onConfirm={this.onConfirmSelect.bind(this, 'addressInfo')}/>
    </View>)
  }
}
